﻿using System;
using UnityEngine.Networking;

namespace Core.Network
{
    public class WebRequestTask : AbstractTask, IWebTask, IAwake<string, Action<IWebTask>>
    {
        public string Uri { get; private set; }

        public byte[] Data { get; private set; }

        public float ElapsedTime { get; private set; }

        private Action<IWebTask> func;
        private UnityWebRequest request;
        private DateTime startTime;

        public void Awake(string uri, Action<IWebTask> func)
        {
            Uri = uri;
            this.func = func;
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            Uri = string.Empty;
            func = null;

            Data = null;
            request = null;
        }

        public override void Start()
        {
            Status = ETaskStatus.Doing;
            startTime = DateTime.Now;

            request = UnityWebRequest.Get(Uri);
            request.SendWebRequest();
        }

        public override void Update()
        {
            if (request == null || request.isDone == false)
            {
                return;
            }

            ElapsedTime = (float)(DateTime.Now - startTime).TotalSeconds;

            if (request.result == UnityWebRequest.Result.Success)
            {
                Description = request.error;

                Status = ETaskStatus.Done;
                Data = request.downloadHandler.data;
            }
            else
            {
                Status = ETaskStatus.Error;
                Data = null;
            }
        }

        public override void Finish()
        {
            func?.Invoke(this);
        }

    }
}
